package org.jeecg.chase.modules.api;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.chase.common.utils.GetPostUntil;
import org.jeecg.chase.modules.adhuser.entity.AdhUser;
import org.jeecg.chase.modules.adhuser.service.IAdhUserService;
import org.jeecg.chase.modules.advert.entity.AdhAdvert;
import org.jeecg.chase.modules.advert.service.IAdhAdvertService;
import org.jeecg.chase.modules.api.service.ApiService;
import org.jeecg.chase.modules.entity.AdhCouponInfo;
import org.jeecg.chase.modules.entity.AdhCouponUserView;
import org.jeecg.chase.modules.entity.AdhShopCategory;
import org.jeecg.chase.modules.merch.entity.AdhMerchInfo;
import org.jeecg.chase.modules.merch.entity.AdhUserMerchFocus;
import org.jeecg.chase.modules.merch.service.IAdhMerchInfoService;
import org.jeecg.chase.modules.merch.service.IAdhUserMerchFocusService;
import org.jeecg.chase.modules.model.AdhShopCategoryApiTree;
import org.jeecg.chase.modules.order.entity.AdhCouponOrder;
import org.jeecg.chase.modules.order.service.IAdhCouponOrderService;
import org.jeecg.chase.modules.service.IAdhCouponInfoService;
import org.jeecg.chase.modules.service.IAdhCouponUserViewService;
import org.jeecg.chase.modules.service.IAdhShopCategoryService;
import org.jeecg.chase.modules.utils.QRCodeUtil;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 轮播广告查询
 * @Author: jeecg-boot
 * @Date: 2022-01-08
 * @Version: V1.0
 */
@Api(tags = "轮播广告查询")
@RestController
@RequestMapping("/api")
@Slf4j

public class ApiController {
    @Autowired
    private IAdhUserMerchFocusService adhUserMerchFocusService;
    @Autowired
    private IAdhAdvertService adhAdvertService;
    @Autowired
    private IAdhMerchInfoService adhMerchInfoService;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private IAdhShopCategoryService adhShopCategoryService;
    @Autowired
    private IAdhUserService adhUserService;

    @Autowired
    private IAdhCouponInfoService iAdhCouponInfoService;

    @Autowired
    private IAdhCouponOrderService iAdhCouponOrderService;
    @Autowired
    private IAdhCouponUserViewService iAdhCouponUserViewService;

    @Autowired
    private ApiService apiService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appKey}")
    private String appKey;

    /**
     * 前端需先调用官方wx.login接口获取登录凭证code ,然后调用该接口 获取用户秘钥 sessionKey
     *
     * @param js_code
     * @return
     * @throws JSONException
     */
    @ResponseBody
    @PostMapping("/initWxLogin")
    public Result<?> initWxLogin(@RequestParam(value = "js_code", required = true) String js_code) throws JSONException {
        //测试数据code
        //    js_code = "081ZQ3f91fr9VM1HYdb91y93f91ZQ3fU";
        //微信获取session_key接口地址
        String wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session";
        String param = "appid=" + appId + "&secret=" + appKey + "&js_code=" + js_code + "&grant_type=authorization_code";
        String jsonString = GetPostUntil.sendGet(wxLoginUrl, param);
        System.out.println(jsonString);
        //因为json字符串是大括号包围，所以用JSONObject解析
        JSONObject json = JSONObject.parseObject(jsonString);
        String session_key = json.getString("session_key");
        System.out.println("session_key：" + session_key);
        return Result.OK(json);
    }

    /**
     * 小程序前端通过官方getPhoneNumber获取encryptedData，iv
     * 小程序前端通过参数**【encryptedData】 、【iv】 、【sessionKey】** 发送请求后端接口，获取手机号等信息
     *
     * @param openId
     * @param nickName
     * @param gender
     * @param avatarUrl
     * @return
     * @throws UnsupportedEncodingException
     * @throws InvalidAlgorithmParameterException
     * @throws JSONException
     */
    @ResponseBody
    @PostMapping(value = "/decodeUserInfo")
    public Result<?> decodeUserInfo(@RequestParam(required = true, value = "openId") String openId,
                                    @RequestParam(value = "nickName") String nickName,
                                    @RequestParam(value = "gender") String gender,
                                    @RequestParam(value = "avatarUrl") String avatarUrl) throws UnsupportedEncodingException, InvalidAlgorithmParameterException, JSONException {
        //AESUtils微信获取手机号解密工具类
        Map userInfo = new HashMap();
        AdhUser user = adhUserService.getUserInfoByOpenId(openId);
        if (user != null) {
            if (StringUtils.isNotBlank(avatarUrl)) {
                user.setUserAvtor(avatarUrl);
            }
            if (StringUtils.isNotBlank(nickName)) {
                user.setNickName(nickName);
            }
            if (StringUtils.isNotBlank(gender)) {
                user.setSex(gender);
            }
            user.setUpdateBy("system");
            user.setUpdateTime(new Date());
            adhUserService.updateById(user);
            String userPhone = user.getUserPhone();
            if (StringUtils.isBlank(userPhone)) {
                userInfo.put("isMerch", "0");//普通会员
                userInfo.put("merchInfo", null);
            } else {
                List<AdhMerchInfo> list = adhMerchInfoService.getMerchInfoByPhoneNumber(userPhone);
                if (list != null && list.size() > 0) {
                    userInfo.put("isMerch", "1");//商家会员
                    userInfo.put("merchInfo", list.get(0));
                } else {
                    userInfo.put("isMerch", "0");//普通会员
                    userInfo.put("merchInfo", null);
                }
            }
        } else {
            user = new AdhUser();
            user.setOpenId(openId);
            user.setUserType("1");//普通用户
            if (StringUtils.isNotBlank(avatarUrl)) {
                user.setUserAvtor(avatarUrl);
            }
            if (StringUtils.isNotBlank(nickName)) {
                user.setNickName(nickName);
            }
            if (StringUtils.isNotBlank(gender)) {
                user.setSex(gender);
            }
            user.setCreateBy("system");
            user.setCreateTime(new Date());
            user.setUpdateBy("system");
            user.setUpdateTime(new Date());
            adhUserService.save(user);
            userInfo.put("isMerch", "0");//普通会员
            userInfo.put("merchInfo", null);
        }

        userInfo.put("user", user);
        return Result.OK(user);
    }

    /**
     * 小程序调用该接口，查询广告信息
     *
     * @return
     */
    @RequestMapping(value = "/adhAdvert/getAllAdhAdvert", method = RequestMethod.GET)
    public Result<?> getAllAdhAdvert() {
        QueryWrapper<AdhAdvert> queryWrapper = new QueryWrapper<AdhAdvert>();
        queryWrapper.eq("adh_advert_status", "1");
        queryWrapper.orderByAsc("adh_advert_sort");
        List<AdhAdvert> list = adhAdvertService.list(queryWrapper);
        return Result.OK(list);
    }

    /**
     * 小程序：主要用于判断openID是商家账号还是普通用户，如果是商家手机号，则返回商家信息
     *
     * @param openId
     * @return
     */
    @RequestMapping(value = "/adhUser/identificate", method = RequestMethod.GET)
    public Result<?> identificate(@RequestParam(name = "openId", required = true) String openId) {
        Map m = new HashMap();
        AdhUser user = adhUserService.getUserInfoByOpenId(openId);
        if (user == null) {
            return Result.error("500", "会员信息不存在！请先登录小程序注册！");
        }
        String phoneNumber = user.getUserPhone();
        if (StringUtils.isBlank(phoneNumber)) {
            m.put("merchInfo", null);
            m.put("isMerch", "0");
            return Result.OK(m);
        } else {
            List<AdhMerchInfo> list = adhMerchInfoService.getMerchInfoByPhoneNumber(phoneNumber);
            if (list != null && list.size() > 0) {
                //商家信息返回和标记当前手机号是商家手机号
                m.put("merchInfo", list.get(0));
                m.put("userInfo", user);
                m.put("isMerch", "1");//商家标记
                return Result.OK(m);
            } else {
                m.put("merchInfo", null);
                m.put("isMerch", "0");
                return Result.OK(m);
            }
        }
    }

    /**
     * 小程序：根据商家的ID 查询商家基本信息后，主要用户展示商家首页的信息，
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "商家基本信息查询", notes = "商家基本信息查询")
    @GetMapping(value = "/adhShop/queryByShopId")
    public Result<?> queryByShopId(@RequestParam(name = "id", required = true) String id) {
        AdhMerchInfo adhMerchInfo = adhMerchInfoService.getById(id);
        if (adhMerchInfo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(adhMerchInfo);
    }

    @RequestMapping(value = "/adhCitys/list", method = RequestMethod.GET)
    public Result<?> getAdhCitys() {
        try {
            List<DictModel> ls = sysDictService.getDictItems("merch_citys");
            if (ls == null) {
                return Result.error("数据不存在或不正确");
            }
            return Result.OK(ls);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("查询失败");
        }
    }

    @RequestMapping(value = "/adhCategory/queryCategoryForWeChatIndex", method = RequestMethod.POST)
    @AutoLog(value = "首页查询分类下的优惠券信息", operateType = 1)
    public Result<?> queryCategoryForWeChatIndex(@RequestBody JSONObject jsonObject) {
        try {
            String city = jsonObject.getString("city");
            if (StringUtils.isBlank(city)) {
                return Result.error("查询参数错误");
            }
            List<AdhShopCategory> list = adhShopCategoryService.queryCategoryForWeChatIndex();
            for (AdhShopCategory cate : list) {
                //查询每个分类下的商户劵信息
                String cateId = cate.getId();
                List<Map<String, Object>> list1 = adhShopCategoryService.queryMerchCoupponByCategoryAndCity(cateId, city);
                cate.setCouponList(list1);
            }
            return Result.OK(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询出错");
        }
    }

    @RequestMapping(value = "/adhCategory/querySubCategory", method = RequestMethod.POST)
    @AutoLog(value = "首页主分类", operateType = 1)
    public Result<?> queryMasterCategory(@RequestBody JSONObject jsonObject) {
        try {
            String categoryId = jsonObject.getString("categoryId");
            if (StringUtils.isBlank(categoryId)) {
                return Result.error("查询参数错误");
            }
            String city = jsonObject.getString("city");
            if (StringUtils.isBlank(city)) {
                return Result.error("查询参数错误");
            }
            List<AdhShopCategory> list = adhShopCategoryService.querySubCategory(categoryId);
            for (AdhShopCategory cate : list) {
                //查询每个子分类下的商户劵信息
                String cateId = cate.getId();
                List<Map<String, Object>> list1 = adhShopCategoryService.queryMerchCoupponByCategoryAndCity(cateId, city);
                cate.setCouponList(list1);
            }
            return Result.OK(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询出错");
        }
    }

    @RequestMapping(value = "/adhCategory/queryMasterCategory", method = RequestMethod.GET)
    @AutoLog(value = "首页子分类", operateType = 1)
    public Result<?> querySubCategory() {
        try {
            List<AdhShopCategory> list = adhShopCategoryService.queryCategoryForWeChatIndex();
            return Result.OK(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询出错");
        }
    }
    @RequestMapping(value = "/adhCategory/queryMerchInfoByCategory", method = RequestMethod.POST)
    @AutoLog(value = "按照城市和分类id查询商户列表信息", operateType = 1)
    public Result<?> queryMerchInfoByCategory(@RequestBody JSONObject jsonObject) {
        try {
            String city = jsonObject.getString("city");
            String cateId = jsonObject.getString("cateId");
            if (StringUtils.isBlank(city)) {
                return Result.error("查询参数错误");
            }
            if (StringUtils.isBlank(cateId)) {
                return Result.error("查询参数错误");
            }
            List<Map<String, Object>> list1 = adhShopCategoryService.queryMerchByCategoryAndCity(cateId, city);
            return Result.OK(list1);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询出错");
        }
    }

    @RequestMapping(value = "/adhCoupon/searchCoupon", method = RequestMethod.POST)
    @AutoLog(value = "首页查询分类下的优惠券信息", operateType = 1)
    public Result<List<Map<String, Object>>> searchCoupon(@RequestBody JSONObject jsonObject) {
        Result<List<Map<String, Object>>> result = new Result<>();
        String searchKey = jsonObject.getString("searchKey");
        List<Map<String, Object>> list = adhShopCategoryService.searchCoupon(searchKey);
        result.setResult(list);
        result.setSuccess(true);
        return result;
    }

    @RequestMapping(value = "/adhCategory/list", method = RequestMethod.GET)
    @AutoLog(value = "分类列表查询", operateType = 1)
    public Result<?> queryList() {
        try {
            LambdaQueryWrapper<AdhShopCategory> query = new LambdaQueryWrapper<AdhShopCategory>();
            query.orderByAsc(AdhShopCategory::getCategoryOrder);
            query.eq(AdhShopCategory::getCategoryStatus, true);
            List<AdhShopCategory> list = this.adhShopCategoryService.list(query);
            List<AdhShopCategoryApiTree> treeList = new ArrayList<>();
            getTreeList(treeList, list, null);
            return Result.OK(treeList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询出错");
        }
    }

    private void getTreeList(List<AdhShopCategoryApiTree> treeList, List<AdhShopCategory> metaList, AdhShopCategoryApiTree temp) {
        for (AdhShopCategory adhShopCategory : metaList) {
            String tempPid = adhShopCategory.getParentId();
            AdhShopCategoryApiTree tree = new AdhShopCategoryApiTree(adhShopCategory);
            List<Map<String, Object>> merchList = this.apiService.queryMerchList(tree.getId());
            tree.setMerchList(merchList);
            if (temp == null && oConvertUtils.isEmpty(tempPid)) {
                treeList.add(tree);
                if (tree.getCategoryLevel() != 2) {
                    getTreeList(treeList, metaList, tree);
                }
            } else if (temp != null && tempPid != null && tempPid.equals(temp.getId())) {
                temp.getChildren().add(tree);
                if (tree.getCategoryLevel() != 2) {
                    getTreeList(treeList, metaList, tree);
                }
            }
        }
    }

    /**
     * 小程序：用户关注商家信息
     *
     * @param json POST请求参数：openId  微信openId，merchId 商家ID
     * @return
     */
    @ApiOperation(value = "用户关注商家", notes = "用户关注商家")
    @PostMapping(value = "/adhUser/focusMerchInfo")
    public Result<?> focusMerchInfo(@RequestBody JSONObject json) {
        Result<?> result = new Result<>();
        String openId = json.getString("openId");
        String merchId = json.getString("merchId");
        AdhUser user = adhUserService.getUserInfoByOpenId(openId);
        if (user == null) {
            return Result.error("会员信息不存在！");
        } else {
            String userId = user.getId();
            List<Map<String, Object>> list = adhMerchInfoService.getFocusMerchInfoByUserIdAndMerchId(merchId, userId);
            if (list != null && list.size() > 0) {
                LambdaQueryWrapper<AdhUserMerchFocus> wrapper = new LambdaQueryWrapper<AdhUserMerchFocus>();
                wrapper.eq(AdhUserMerchFocus::getMerchId, merchId);
                wrapper.eq(AdhUserMerchFocus::getUserId, userId);
                adhUserMerchFocusService.remove(wrapper);
                return Result.OK("取消关注成功！");
            } else {
                AdhUserMerchFocus merchFocus = new AdhUserMerchFocus();
                merchFocus.setMerchId(merchId);
                merchFocus.setUserId(userId);
                adhUserMerchFocusService.save(merchFocus);
                return Result.OK("关注成功");
            }
        }
    }

    /**
     * 小程序：获取用户关注商家信息
     *
     * @param json POST请求参数：phoneNumber 手机号
     * @return
     */
    @ApiOperation(value = "查询用户已关注商家", notes = "查询用户已关注商家")
    @PostMapping(value = "/adhUser/queryFocusMerchInfoList")
    public Result<?> queryFocusMerchInfoList(@RequestBody JSONObject json) {
        Result<?> result = new Result<>();
        String openId = json.getString("openId");
        AdhUser user = adhUserService.getUserInfoByOpenId(openId);
        if (user == null) {
            return Result.error("会员信息不存在！");
        } else {
            String userId = user.getId();
            List<Map<String, Object>> list = adhMerchInfoService.getFocusMerchInfoByUserId(userId);
            ArrayList<Map<String, Object>> resultList = new ArrayList<>();
            list.forEach(map -> {
                String merchId = map.get("id").toString();
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.putAll(map);
                LambdaQueryWrapper<AdhCouponInfo> queryWrapper = new LambdaQueryWrapper<AdhCouponInfo>();
                queryWrapper.eq(AdhCouponInfo::getMerchId, merchId);
                queryWrapper.eq(AdhCouponInfo::getCouponStatus, 2);
                List<AdhCouponInfo> couponInfoList = this.iAdhCouponInfoService.list(queryWrapper);
                hashMap.put("couponList", couponInfoList);
                resultList.add(hashMap);
            });
            return Result.OK(resultList);
        }
    }

    @ApiOperation(value = "绑定手机号", notes = "绑定手机号")
    @PostMapping(value = "/adhUser/bindPhone")
    public Result<?> bindUserPhone(@RequestBody JSONObject json) {
        Result<?> result = new Result<>();
        String openId = json.getString("openId");
        String phoneNumber = json.getString("phoneNumber");
        AdhUser user = adhUserService.getUserInfoByOpenId(openId);
        if (user == null) {
            return Result.error("会员信息不存在！");
        } else {
            user.setUserPhone(phoneNumber);
            List<AdhMerchInfo> list = adhMerchInfoService.getMerchInfoByPhoneNumber(phoneNumber);
            if (list != null && list.size() > 0) {
                user.setUserType("2");
            }
            user.setUpdateTime(new Date());
            adhUserService.updateById(user);
            return Result.OK(user);
        }
    }

    @ApiOperation(value = "完善用户信息", notes = "完善用户信息")
    @PostMapping(value = "/adhUser/updateUserInfo")
    public Result<?> updateUserInfo(@RequestBody JSONObject json) {
        Result<?> result = new Result<>();
        String openId = json.getString("openId");
        String sex = json.getString("sex");
        String email = json.getString("email");
        String nickName = json.getString("nickName");
        String userName = json.getString("userName");
        AdhUser user = adhUserService.getUserInfoByOpenId(openId);
        if (user == null) {
            return Result.error("会员信息不存在！");
        } else {
            if (StringUtils.isNotBlank(sex)) {
                user.setSex(sex);
            }
            if (StringUtils.isNotBlank(email)) {
                user.setEmail(email);
            }
            if (StringUtils.isNotBlank(nickName)) {
                user.setNickName(nickName);
            }
            if (StringUtils.isNotBlank(userName)) {
                user.setUserName(userName);
            }
            adhUserService.updateById(user);
            return Result.OK(user);
        }
    }

    /**
     * 小程序，根据商户id和openId 获取优惠券列表
     *
     * @param merchId
     * @param openId
     * @return org.jeecg.common.api.vo.Result<?>
     * @author leikai
     * @date 2022/03/07/0007 21:33
     */
    @ApiOperation(value = "根据商户获取优惠券列表", notes = "根据商户获取优惠券列表")
    @GetMapping(value = "/adhCoupon/queryCouponList")
    public Result<?> queryCouponList(@RequestParam(name = "merchId", required = true) String merchId,
                                     @RequestParam(name = "openId", required = false) String openId) {
        try {
            openId = "";
            List<Map<String, Object>> mapList = this.iAdhCouponInfoService.queryCouponList(merchId, openId);
            return Result.OK(mapList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询出错");
        }
    }

    /**
     * 根据商户Id获取商户详情
     *
     * @param merchId
     * @return org.jeecg.common.api.vo.Result<?>
     * @author leikai
     * @date 2022/03/10/0010 16:19
     */
    @ApiOperation(value = "根据商户Id获取商户详情", notes = "根据商户Id获取商户详情")
    @GetMapping(value = "/adhMerch/getMerchInfo")
    public Result<?> getMerchInfo(@RequestParam(name = "merchId", required = true) String merchId,
                                  @RequestParam(name = "openId", required = true) String openId) {
        try {
            AdhUser user = adhUserService.getUserInfoByOpenId(openId);
            String userId = "";
            if (user != null) {
                userId = user.getId();
            }
            Map<String, Object> merchInfo = this.apiService.getMerchInfo(merchId, userId);
            return Result.OK(merchInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询出错");
        }
    }

    /**
     * 根据优惠券id获取优惠券详情
     *
     * @param couponId
     * @return org.jeecg.common.api.vo.Result<?>
     * @author leikai
     * @date 2022/03/10/0010 17:51
     */
    @ApiOperation(value = "根据优惠券id获取优惠券详情", notes = "根据优惠券id获取优惠券详情")
    @GetMapping(value = "/adhCoupon/getCouponInfo")
    public Result<?> getCouponInfo(@RequestParam(name = "couponId", required = true) String couponId) {
        try {
            AdhCouponInfo couponInfo = this.iAdhCouponInfoService.getById(couponId);
            return Result.OK(couponInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询出错");
        }
    }

    /**
     * 优惠券领取
     *
     * @param param
     * @return org.jeecg.common.api.vo.Result<?>
     * @author leikai
     * @date 2022/03/12/0012 17:20
     */
    @ApiOperation(value = "优惠券领取", notes = "优惠券领取")
    @PostMapping(value = "/adhCoupon/receiveCoupon")
    public Result<?> receiveCoupon(@RequestBody Map<String, String> param) {
        Result<Object> result = new Result<>();
        String lockKey = "";
        String openId = param.get("openId");
        String merchId = param.get("merchId");
        String couponId = param.get("couponId");
        AdhCouponInfo couponInfo = iAdhCouponInfoService.getById(couponId);
        if(couponInfo==null){
            result.setCode(500);
            result.setMessage("该优惠券不存在");
            result.setSuccess(false);
        }else{
            if (StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(merchId) && StringUtils.isNotBlank(couponId)) {
                lockKey = "adh_" + couponId;
                boolean adh = redisUtil.setIfAbsent(lockKey, "adh", 30L, TimeUnit.SECONDS);
                if (!adh) {
                    result.setCode(600);
                    result.setMessage("领取人数较多，请稍等再试");
                    result.setSuccess(false);
                } else {
                    try {
                        AdhUser user = adhUserService.getUserInfoByOpenId(openId);
                        if (user == null) {
                            result.error500("会员信息不存在！请先登录小程序注册！");
                        } else {
                            //查询看是否是报名券，如果是报名券，则获取报名姓名，手机号，邮箱地址，备注
                            if("5".equals(couponInfo.getCouponType())){
                                String bmName = param.get("bmName");
                                String bmEmail = param.get("bmEmail");
                                String bmPhone = param.get("bmPhone");
                                String bmRemark = param.get("bmRemark");
                                if(StringUtils.isBlank(bmName)){
                                    result.setCode(500);
                                    result.setMessage("报名姓名不能为空");
                                    result.setSuccess(false);
                                }else if(StringUtils.isBlank(bmEmail)){
                                    result.setCode(500);
                                    result.setMessage("报名邮箱地址不能为空");
                                    result.setSuccess(false);
                                }else if(StringUtils.isBlank(bmPhone)){
                                    result.setCode(500);
                                    result.setMessage("报名电话号码不能为空");
                                    result.setSuccess(false);
                                }else{
                                    Map<String, String> map = this.apiService.receiveBmCoupon(merchId, couponId, user,bmName,bmEmail,bmPhone,bmRemark);
                                    if (map.get("code").equals("200")) {
                                        result.setMessage("报名成功");
                                        result.setCode(200);
                                        result.setSuccess(true);
                                    } else {
                                        result.setMessage(map.get("message"));
                                        result.setCode(Integer.parseInt(map.get("code")));
                                        result.setSuccess(false);
                                    }
                                }


                            }else{
                                Map<String, String> map = this.apiService.receiveCoupon(merchId, couponId, user);
                                if (map.get("code").equals("200")) {
                                    result.setMessage("领取成功");
                                    result.setCode(200);
                                    result.setSuccess(true);
                                } else {
                                    result.setMessage(map.get("message"));
                                    result.setCode(Integer.parseInt(map.get("code")));
                                    result.setSuccess(false);
                                }
                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        result.error500("领取失败");
                    } finally {
                        redisUtil.remove(lockKey);
                    }
                }
            }
        }

        return result;
    }

    /**
     * 优惠券二维码和条形码获取
     *
     * @param couponNo 优惠券订单号
     * @return org.jeecg.common.api.vo.Result<?>
     * @author leikai
     * @date 2022/03/12/0012 17:20
     */
    @ApiOperation(value = "优惠券二维码和条形码获取", notes = "优惠券二维码和条形码获取")
    @GetMapping(value = "/adhCoupon/getCouponQrCode")
    public Result<?> getCouponQrCode(@RequestParam(name = "couponNo", required = true) String couponNo,
                                     @RequestParam(name = "qrWidth", required = false) Integer width,
                                     @RequestParam(name = "qrHeight", required = false) Integer height,
                                     @RequestParam(name = "barWidth", required = false) Integer barWidth,
                                     @RequestParam(name = "barHeight", required = false) Integer barHeight) {
        try {
            LambdaQueryWrapper<AdhCouponOrder> queryWrapper = new LambdaQueryWrapper<AdhCouponOrder>();
            queryWrapper.eq(AdhCouponOrder::getCouponNo, couponNo);
            AdhCouponOrder couponOrder = this.iAdhCouponOrderService.getOne(queryWrapper);
            if (couponOrder == null) {
                return Result.error("没有该优惠券信息");
            }
            String content = couponOrder.getCouponNo();
            String qrCode = null;
            String barCode = null;
            if (width == null || height == null) {
                qrCode = QRCodeUtil.getBase64QRCode(content);
            } else {
                qrCode = QRCodeUtil.getBase64QRCode(content, width, height);
            }
            if (barWidth == null || height == null) {
                barCode = QRCodeUtil.getBarCode(content);
            } else {
                barCode = QRCodeUtil.getBarCode(content, barWidth, barHeight);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("qrCode", qrCode);
            resultMap.put("barCode", barCode);
            resultMap.put("couponNo", content);
            resultMap.put("validBeginTime", sdf.format(couponOrder.getValidBeginTime()));
            resultMap.put("validEndTime", sdf.format(couponOrder.getValidEndTime()));
            resultMap.put("useDesc", couponOrder.getUseDesc());
            resultMap.put("merchName", couponOrder.getMerchName());
            resultMap.put("couponName", couponOrder.getCouponName());
            resultMap.put("couponType", couponOrder.getCouponType());
            return Result.OK(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询出错");
        }
    }

    /**
     * 优惠券核销
     *
     * @param couponNo 核销订单号
     * @param openId
     * @return org.jeecg.common.api.vo.Result<?>
     * @author leikai
     * @date 2022/03/12/0012 18:16
     */
    @ApiOperation(value = "优惠券核销", notes = "优惠券核销")
    @GetMapping(value = "/adhCoupon/getCouponCheck")
    public Result<?> getCouponCheck(@RequestParam(name = "couponNo", required = true) String couponNo,
                                    @RequestParam(name = "openId", required = true) String openId) {
        try {
            LambdaQueryWrapper<AdhUser> uQueryWrapper = new LambdaQueryWrapper<AdhUser>();
            uQueryWrapper.eq(AdhUser::getOpenId, openId);
            uQueryWrapper.eq(AdhUser::getUserType, "2");
            AdhUser user = adhUserService.getOne(uQueryWrapper);
            if (user == null) {
                return Result.error("该商家不存在");
            }
            List<AdhMerchInfo> list = adhMerchInfoService.getMerchInfoByPhoneNumber(user.getUserPhone());
            if (list == null || list.size() <= 0) {
                return Result.error("当前商家用户所关联的商家不存在");
            }
            AdhMerchInfo merchInfo = list.get(0);
            LambdaQueryWrapper<AdhCouponOrder> queryWrapper = new LambdaQueryWrapper<AdhCouponOrder>();
            queryWrapper.eq(AdhCouponOrder::getCouponNo, couponNo);
            queryWrapper.eq(AdhCouponOrder::getMerchId, merchInfo.getId());
            AdhCouponOrder couponOrder = this.iAdhCouponOrderService.getOne(queryWrapper);
            if (couponOrder == null) {
                return Result.error("该优惠券不存在或不适用于该商家");
            }
            couponOrder.setCheckDate(new Date());
            couponOrder.setCheckUser(user.getUserPhone());
            couponOrder.setUseStatus(1);
            couponOrder.setUpdateTime(new Date());
            this.iAdhCouponOrderService.updateById(couponOrder);
            return Result.OK("核销成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("核销出错");
        }
    }

    /**
     * @param openId
     * @param useStatus
     * @return org.jeecg.common.api.vo.Result<?>
     * @author leikai
     * @date 2022/03/15/0015 19:46
     */
    @ApiOperation(value = "我的优惠券", notes = "我的优惠券")
    @GetMapping(value = "/adhCoupon/queryCouponOrder")
    public Result<?> queryCouponOrder(@RequestParam(name = "openId") String openId,
                                      @RequestParam(name = "useStatus", required = false) Integer useStatus) {
        try {
            LambdaQueryWrapper<AdhUser> uQueryWrapper = new LambdaQueryWrapper<AdhUser>();
            uQueryWrapper.eq(AdhUser::getOpenId, openId);

            AdhUser user = adhUserService.getOne(uQueryWrapper);
            if (user == null) {
                return Result.error("该商家不存在");
            }
            List<?> list = this.apiService.queryCouponOrder(user.getId(), useStatus);
            return Result.OK(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 商家优惠券
     *
     * @param merchId
     * @param couponStatus
     * @return org.jeecg.common.api.vo.Result<?>
     * @author leikai
     * @date 2022/03/15/0015 19:51
     */
    @ApiOperation(value = "商家优惠券", notes = "商家优惠券")
    @GetMapping(value = "/adhCoupon/queryCouponMerch")
    public Result<?> queryCouponMerch(@RequestParam(name = "merchId") String merchId,
                                      @RequestParam(name = "couponStatus", required = true) String couponStatus) {
        try {
            LambdaQueryWrapper<AdhCouponInfo> queryWrapper = new LambdaQueryWrapper<AdhCouponInfo>();
            queryWrapper.eq(AdhCouponInfo::getMerchId, merchId);
            queryWrapper.eq(AdhCouponInfo::getCouponStatus, couponStatus);
            List<AdhCouponInfo> pageList = this.iAdhCouponInfoService.list(queryWrapper);
            return Result.OK(pageList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    @ApiOperation(value = "我的核销记录", notes = "我的核销记录")
    @GetMapping(value = "/adhCoupon/queryCouponCheck")
    public Result<?> queryCouponCheck(@RequestParam(name = "openId") String openId) {
        try {
            LambdaQueryWrapper<AdhUser> uQueryWrapper = new LambdaQueryWrapper<AdhUser>();
            uQueryWrapper.eq(AdhUser::getOpenId, openId);
            AdhUser user = adhUserService.getOne(uQueryWrapper);
            if (user == null) {
                return Result.error("该商家不存在");
            }
            List<?> list = this.apiService.queryCouponCheck(user.getUserPhone());
            return Result.OK(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }
    @ApiOperation(value = "展示券浏览", notes = "展示券浏览")
    @PostMapping(value = "/adhCoupon/couponView")
    public Result<?> couponView(@RequestBody JSONObject param) {
        String openId = param.getString("openId");
        String couponId = param.getString("couponId");
        AdhUser user =  adhUserService.getUserInfoByOpenId(openId);
        if (user == null) {
            return Result.error("用户信息不存在");
        }
        AdhCouponInfo coupon =  iAdhCouponInfoService.getById(couponId);
        if(coupon==null){
            return Result.error("券信息不存在");
        }
        AdhCouponUserView view = new AdhCouponUserView();
        view.setCouponId(couponId);
        view.setCouponName(coupon.getCouponName());
        view.setCreateBy("system");
        view.setCreateTime(new Date());
        view.setNickName(user.getNickName());
        view.setUserAvtor(user.getUserAvtor());
        view.setUserPhone(user.getUserPhone());
        iAdhCouponUserViewService.save(view);
        return Result.OK("记录用户券浏览成功");
    }
}
